@{
ViewData["Titel"] = "日志管理";
var roleType = ViewData["Role"].ToString();
}

@*
<!DOCTYPE html>*@


@*<head>
	<meta name="viewport" content="width=device-width" />
	<title>Index</title>
</head>*@
<h2 style="margin:20px 0">日志列表</h2>
<hr />
<form method="post" enctype="multipart/form-data" asp-controller="InfoLog" asp-action="FileRecover">
	<div>
		@*<p>
			<a asp-action="Create">Create New</a>
		</p>*@
		<table class="table  table-hover">
			<thead>
				<tr>
					<th class="text-center">
						用户名
					</th>
					<th class="text-center">
						用户类别
					</th>
					<th class="text-center">
						操作类型
					</th>
					<th class="text-center">
						操作时间
					</th>
					<th class="text-center">
						备注
					</th>
					<th></th>
				</tr>
			</thead>
			<tbody id="userList"></tbody>
		</table>
		<div class="row ">
			<div id="Page" class="col-md-6 col-md-offset-3 "></div>
		</div>
		@if (roleType == "User")
		{
		<div class="row">
			<input type="button" id="btnBackUp" class="  btn btn-default " style="width:82px" value="备份日志" />
			@*<span class=" btn btn-default " style="position: relative;
        display: inline-block;
        overflow: hidden;cursor:pointer">
				<span style="cursor:pointer">上传日志</span>
				<input type="file" name="fileRecover" id="fileRecover" style="position:absolute;
                right: 0px;
                top: 0px;
                opacity: 0;cursor:pointer;
                -ms-filter: 'alpha(opacity=0)';
                font-size: 200px;">
			</span>
			<div id="btnRecover" class="btn btn-default" style="width:82px">恢复日志</div>*@
			<div id="href" class="btn btn-default" style="width:140px;margin-left: 40px;" onclick="(()=>{location.href='/InfoLog/Backup'})()">点击去操作全库</div>
		</div>
		<p style="height:10px;"></p>
		
		<!-- <div class="row">
			<input type="button" id="btnBackUpAll" class="  btn btn-default " value="备份全库" />
			<span class=" btn btn-default " style="position: relative;
        display: inline-block;
        overflow: hidden;cursor:pointer">
				<span style="cursor:pointer">上传全库</span>
				<input type="file" name="fileRecoverAll" id="fileRecoverAll" style="position:absolute;
                right: 0px;
                top: 0px;
                opacity: 0;cursor:pointer;
                -ms-filter: 'alpha(opacity=0)';
                font-size: 200px;">
			</span>
			<div id="btnRecoverAll" class="btn btn-default">恢复全库</div>
		</div> -->
		}

	</div>
</form>
<script src="~/lib/jquery/jquery-1.12.4.js"></script>
<script src="~/Content/layui/layui.js"></script>
<script>
	//Base64编码
	function Base64() {
		// private property
		_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		// public method for encoding
		this.encode = function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = _utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
					_keyStr.charAt(enc1) +
					_keyStr.charAt(enc2) +
					_keyStr.charAt(enc3) +
					_keyStr.charAt(enc4);
			}
			return output;
		};

		// public method for decoding
		this.decode = function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = _keyStr.indexOf(input.charAt(i++));
				enc2 = _keyStr.indexOf(input.charAt(i++));
				enc3 = _keyStr.indexOf(input.charAt(i++));
				enc4 = _keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = _utf8_decode(output);
			return output;
		};

		// private method for UTF-8 encoding
		_utf8_encode = function(string) {
			string = string.toString().replace(/\r\n/g, "\n");
			var utftext = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					utftext += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				} else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}
			return utftext;
		};

		// private method for UTF-8 decoding
		_utf8_decode = function(utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while (i < utftext.length) {
				c = utftext.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i + 1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = utftext.charCodeAt(i + 1);
					c3 = utftext.charCodeAt(i + 2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		};
	}

	//外部加密
	function ExternalEncrypt(Json, funcBack) {
		console.log(Json)
		var socket = new WebSocket("ws://127.0.0.1:2012/CustomizeEnvelope");
		try {

			socket.onopen = function(msg) {
				socket.send(Json);
			};
			socket.onmessage = function(e) {
				console.log(e.data, "加密");
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function EncryptCertList(back) {
		var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertList");
		try {

			socket.onopen = function(msg) {
				socket.send("1");
			};
			socket.onmessage = function(e) {
				back(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}
	}

	function myPost(url) {
		var body = $(document.body),
			form = $("<form method='post'></form>"),
			input;
		console.log(1);
		form.attr({
			"action": url
		});
		//$.each(args, function (key, value) {
		//    input = $("<input type='hidden'>");
		//    input.attr({ "name": key });
		//    input.val(value);
		//    form.append(input);
		//});

		form.appendTo(document.body);
		form.submit();
		document.body.removeChild(form[0]);
	}

	function _arrayBufferToBase64(buffer) {
		var binary = '';
		var bytes = new Uint8Array(buffer);
		var len = bytes.byteLength;
		for (var i = 0; i < len; i++) {
			binary += String.fromCharCode(bytes[i]);
		}
		return window.btoa(binary);
	}
	$(function() {
		var base64 = new Base64();
		$('#btnBackUp').click(function() {
			myPost("/InfoLog/FileBackUp");
		});
		$('#btnRecover').click(function() {
			var fileObj = document.getElementById("fileRecover").files[0]; // js 获取文件对象
			if (typeof(fileObj) == "undefined" || fileObj.size <= 0) {
				layer.msg("请选择文件");
				return;
			}
			var t = fileObj.name.lastIndexOf(".");
			var fileName = fileObj.name.substring("0", t);
			var fileSuffix = fileObj.name.substring(t + 1);
			console.log(fileName + '.' + fileSuffix + '\n' + fileObj.name);
			if (fileObj.type == "text/plain") {
				var formFile = new FormData();
				formFile.append("file", fileObj);
				var reader = new FileReader();
				var fileBase64 = null;
				reader.onload = function(e) {
					var str = reader.result;
					var t = str.indexOf(",");
					str = str.substring(t + 1);
					console.log(str);
					EncryptCertList((data) => {
						data = JSON.parse(data);
						let CertID = data.CertInfolist[0].CertID;
						var dataPost = {
							fileContent: str,
							fileName: fileName,
							fileSuffix: fileSuffix,
							validatecode:"@ViewBag.ValidateCode"
						}
						console.log(dataPost)
						var External = {
							CertID: CertID,
							//编码
							DataBase64: base64.encode(JSON.stringify(dataPost))
						};
						ExternalEncrypt(JSON.stringify(External), (data) => {
							data = JSON.parse(data);
							console.log(data.contentBase64, "222")
							if (data.error == "Ok") {
								var data1 = {
									// ArrayNo: CertID,
									EncryptData: data.contentBase64
								};
								$.ajax({
									url: "/InfoLog/FileRecover",
									data: data1,
									type: "Post",
									dataType: "json",
									// cache: false, //上传文件无需缓存
									// processData: false, //用于对data参数进行序列化处理 这里必须false
									// contentType: false, //必须
									success: function(result) {
										if (result.state == 'success') {
											layer.msg(result.message);
										} else {
											layer.msg(result.message);
										}
									},
								})



							}
						});
					})
				}
				reader.readAsDataURL(fileObj);

				// var data = formFile;
				// $.ajax({
				// 	url: "/InfoLog/FileRecover",
				// 	data: data,
				// 	type: "Post",
				// 	dataType: "json",
				// 	cache: false, //上传文件无需缓存
				// 	processData: false, //用于对data参数进行序列化处理 这里必须false
				// 	contentType: false, //必须
				// 	success: function(result) {
				// 		if (result.state == 'success') {
				// 			layer.msg(result.message);
				// 		} else {
				// 			layer.msg(result.message);
				// 		}
				// 	},
				// })
			} else {
				layer.msg("请选择正确的文件！");
			}
		});
		$('#btnBackUpAll').click(function() {
			myPost("/InfoLog/BackUpAll");
		});
		$('#btnRecoverAll').click(function() {
			var fileObj = document.getElementById("fileRecoverAll").files[0]; // js 获取文件对象
			if (typeof(fileObj) == "undefined" || fileObj.size <= 0) {
				layer.msg("请选择文件");
				return;
			}
			var t = fileObj.name.lastIndexOf(".");
			var fileName = fileObj.name.substring("0", t);
			var fileSuffix = fileObj.name.substring(t + 1);
			if(fileSuffix != "db"){
				layer.msg("请上传正确的文件");
				return;
			}
			console.log(fileName + '.' + fileSuffix + '\n' + fileObj.name);
			// var formFile = new FormData();
			// formFile.append("file", fileObj);
			var reader = new FileReader();
			// var fileBase64 = null;
			reader.onload = function(e) {
				var str = reader.result;
				var t = str.indexOf(",");
				str = str.substring(t + 1);
				console.log(str);
				EncryptCertList((data) => {
					data = JSON.parse(data);
					let CertID = data.CertInfolist[0].CertID;
					var dataPost = {
						fileContent: str,
						fileName: fileName,
						fileSuffix: fileSuffix,
						
						validatecode:"@ViewBag.ValidateCode"
					}
					console.log(dataPost)
					var External = {
						CertID: CertID,
						//编码
						DataBase64: base64.encode(JSON.stringify(dataPost))
					};
					ExternalEncrypt(JSON.stringify(External), (data) => {
						data = JSON.parse(data);
						console.log(data.contentBase64, "222")
						if (data.error == "Ok") {
							var data1 = {
								// ArrayNo: CertID,
								EncryptData: data.contentBase64
							};
							$.ajax({
								url: "/InfoLog/FileRecoverAll",
								data: data1,
								type: "Post",
								dataType: "json",
								// cache: false, //上传文件无需缓存
								// processData: false, //用于对data参数进行序列化处理 这里必须false
								// contentType: false, //必须
								success: function(result) {
									if (result.state == 'success') {
										window.location.href = '/InfoLog/Index';
										layer.msg(result.message);
									} else {
										layer.msg(result.message);
									}
								},
							})



						}
					});
				})
			}
			reader.readAsDataURL(fileObj);


		});
	});
</script>
<script>
	$(function() {
		$(document).ready(function() {
			//ajax请求后台数据
			getUserList(10, 1);

		});
		var currentPage = 1;
		//数据请求
		function getUserList(PageSize, PageIndex) {
			$.ajax({
				url: "/InfoLog/Index",
				type: 'POST',
				data: {
					PageSize,
					PageIndex
				},
				success: function(result) {
					console.log(result);
					var Items = result.data;
					var total = result.total;
					console.log(total);
					showData(Items);
					pages(total);
				}
			});
		}
		// 展示数据
		function showData(Items) {
			var _html = '';
			console.log(Items);
			$.each(Items, function(i) {
				var Item = Items[i];
				_html += ' <tr class="text-center">';
				_html += '<td>' + Item.userName + '</td >';
				_html += '<td>' + Item.userType + '</td >';
				_html += '<td>' + Item.manageType + '</td >';
				_html += '<td>' + Item.createDate + '</td >';
				_html += '<td>' + Item.remark + '</td >';

			})
			$("#userList").html(_html);

		}
		// 分页条
		function pages(allNum) {
			layui.use(['laypage', 'layer'], function() {
				var laypage = layui.laypage,
					layer = layui.layer;
				laypage.render({
					elem: 'Page',
					count: allNum //数据总数，从服务端得到
						,
					curr: currentPage,
					theme: '#393D49',
					jump: function(obj, first) {
						currentPage = obj.curr;
						//首次不执行
						if (!first) {
							getUserList(10, obj.curr)
						}
					}
				});
			})
		};
	})
</script>
